import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    FlatList,
    ActivityIndicator,
    ListView,
    ScrollView,
    TouchableWithoutFeedback,
    StatusBar,
    AsyncStorage,
} from 'react-native';
import request from '../../request/request';
import Video from 'react-native-video';
import HomeHeader from '../header/HomeHeader';
export default class HomeTab extends Component {

    constructor(props) {
        super(props);
        this.state = {
        	token: '',
            isLoad: false,
            isLoading: 0,
            // 判断视频是否加载完毕
            videoReady: true,
            isPlay: true,
            hasFinish: false,
            lists: '',
            isRefresh: true,
            nomore: true,
            tabIndex: 0,
        };
    }

    componentDidMount(){
        global.HomeTabIndex = this;
        // fetch('https://result.eolinker.com/XPZsElz98c92f9c243e2f760bf17420ef24906430bea331?uri=lindf.com',
        //     {
        //         method: 'POST',
        //     }
        // )
        // .then((response) => response.json())        // json方式解析，如果是text就是 response.text()
        // .then((responseData) => {   // 获取到的数据处理
        //     this.setState({
        //     	hasFinish: true,
        //         lists: responseData.result.lists,
        //     });

        // })
        // .catch((error) => {     // 错误处理
        //     alert(error);
        // })
        // .done();
        request(
            'POST', 
            '', 
            (data)=>{
	            this.setState({
		        	hasFinish: true,
		            lists: data.result.lists,
		        });
                console.log(data.result);
            }
            ,
            (error)=>{
                console.log(error);
            }
        );
    }

    // 头部组件
    _headerComponent() {
        return (
            <View style={{width: '100%'}}>
                <View style={{position: 'relative',marginLeft: -10, marginRight: -10,backgroundColor: '#000'}}>
                    <Video
                        style={{width: '100%',height: 210}}
                        // source={require('../../images/summary_hight.mp4')}
                        source={{uri: "http://www.wws666.com/uploadfile/home2.mp4"}}
                        rate={1.0}                   // 控制暂停/播放，0 代表暂停paused, 1代表播放normal.
                        volume={1.0}                 // 声音的放大倍数，0 代表没有声音，就是静音muted, 1 代表正常音量 normal，更大的数字表示放大的倍数
                        muted={false}                // true代表静音，默认为false.
                        paused={this.state.isPlay}      // true代表暂停，默认为false
                        resizeMode="contain"           // 视频的自适应伸缩铺放行为，
                        repeat={false}                // 是否重复播放
                        playInBackground={false}     // 当app转到后台运行的时候，播放是否暂停
                        playWhenInactive={false}     // [iOS] Video continues to play when control or notification center are shown. 仅适用于IOS
                        onLoadStart={this.loadStart} // 当视频开始加载时的回调函数
                        onLoad={this.setDuration}    // 当视频加载完毕时的回调函数
                        onProgress={this.setTime.bind(this)}    //  进度控制，每250ms调用一次，以获取视频播放的进度
                        onEnd={this.onEnd}           // 当视频播放完毕后的回调函数
                        onError={this.videoError}    // 当视频不能加载，或出错后的回调函数
                    />
                    {
						this.state.isPlay?
			            <TouchableWithoutFeedback onPress={this.goPlay.bind(this)}>
			                <Image style={styles.playBtn} source={require('../../images/play.png')}/>
			            </TouchableWithoutFeedback>
			            :
			            null
                    }
                </View>
                <View>
                    <View style={{
                        backgroundColor: '#ffffff',
                        paddingLeft: 10,
                        paddingRight: 10,
                        flexDirection: 'row',
                        justifyContent: 'space-between'
                    }}>
                        <Text style={{fontSize: 15, color: '#535353', lineHeight: 45}}>鞋匠资讯</Text>
                        <TouchableWithoutFeedback onPress={() => this.props.navigate('NewsList',{
                            id: 1
                        })}>
                            <View>
                                <Text style={{fontSize: 14, color: '#959595', lineHeight: 45}}>更多+</Text>
                            </View> 
                        </TouchableWithoutFeedback>
                    </View>
                    {
                    	this.state.hasFinish?
                    	<ScrollView
	                        style={{
	                            backgroundColor: '#FFFFFF'
	                        }}
	                        horizontal={true}
	                        showsHorizontalScrollIndicator={false}
	                    >
	                        <View style={{minHeight: 190, paddingLeft: 10, flexDirection: 'row'}}>
								{this.renderNewsItem()}
	                        </View>
	                    </ScrollView>
	                    :
	                    <View style={{minHeight: 190, justifyContent: 'center', alignItems: 'center'}}>
							<ActivityIndicator color='#000' />
							<Text style={{fontSize: 13, color: '#000'}}>正在加载...</Text>
						</View>
                    }
                </View>
                <TouchableWithoutFeedback onPress={() => this.props.navigate('PrizeDetail')}>
                    <View>
                        <View style={{minHeight: 90, paddingTop: 10,paddingBottom: 10,backgroundColor: '#eeeeee'}}>
                            <Image style={{
                                width: '100%',
                                height: 70
                            }} source={require('../../images/new.png')}/>
                            <View style={{width: '76%', position: 'absolute', right: 10, top: '50%',marginTop: -5}}>
                                <Text numberOfLines={1} style={{fontSize: 13, color: '#181818', lineHeight: 16}}>恭喜 130xxxx9409
                                    用户获得 1300.58元免单！</Text>
                                <Text numberOfLines={1} style={{fontSize: 13, color: '#181818', lineHeight: 16}}>恭喜 130xxxx9409
                                    用户获得 1300.58元免单</Text>
                            </View>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
                <View style={{
                    backgroundColor: '#ffffff',
                    paddingLeft: 10,
                    paddingRight: 10,
                    flexDirection: 'row',
                    justifyContent: 'space-between'
                }}>
                    <Text style={{fontSize: 15, color: '#535353', lineHeight: 45}}>推荐代理商品 {this.state.token}</Text>
                    {/*<Text style={{fontSize: 14, color: '#959595', lineHeight: 45}}>更多+</Text>*/}
                </View>
            </View>

        );
    }

    // 鞋匠资讯
    renderNewsItem() {
        // 数组
        let itemAry = [];
        // 遍历
        let _this = this;
        for (let i = 0; i<this.state.lists.length; i++) {
            itemAry.push(
                <TouchableWithoutFeedback key={i} onPress={() => this.props.navigate('NewsDetail',{
                    id: _this.state.lists[i].id
                })}>
                    <View style={{width: 250, marginRight: 8, paddingBottom: 5}}>
                        <Image style={{
                            width: 250,
                            height: 140,
                            marginRight: 8,
                            marginBottom: 8,
                            borderRadius: 5
                        }} source={{uri: _this.state.lists[i].src}}/>
                        <Text style={{fontSize: 13, lineHeight: 17, color: '#707070'}} numberOfLines={2}>{_this.state.lists[i].text}</Text>
                    </View>
                </TouchableWithoutFeedback>
            )
        }
        return itemAry;
    }

	// 尾部组件
    _bottomComponent(){
    	if(this.state.isLoading==0){
            return (
           		<TouchableWithoutFeedback onPress={()=>alert('加载更多')}>
					<View style={{flexDirection: 'row', justifyContent: 'center'}}>
	                    <Text style={{lineHeight: 30}}>点击加载更多</Text>
	                </View>
           		</TouchableWithoutFeedback>
            )
        }else if(this.state.isLoading==1){
            return (
                <View style={{flexDirection: 'row', justifyContent: 'center'}}>
                    <Text style={{lineHeight: 30}}>加载中...</Text>
                </View>
            )
        }else if(this.state.isLoading==2){
            return (
                <View style={{flexDirection: 'row', justifyContent: 'center'}}>
                    <Text style={{lineHeight: 30}}>暂无数据</Text>
                </View>
            )
        }
    }

	// 下拉刷新
    _onRefresh(){
        console.log('下拉刷新')
        this.setState({
            isLoad: !this.state.isLoad
        },function(){
            // 请求数据
            setTimeout(()=>{
                this.setState({
                    isLoad: !this.state.isLoad
                });
            },5000)
        });
        
    }

  //   _AsyncStorage(){	
  //   	let _this = this;

		// // AsyncStorage.setItem('token', '这是我存的数据', function (error) {
	 // //      if (error) {
	 // //        alert('存储失败');
	 // //      } else {
	 // //        alert('存储成功');
	 // //      }
	 // //    })
	
  //    	AsyncStorage.getItem('token', function (error, result) {
	 //      if (!error) {
	 //        _this.setState({token: result})
	 //      }else {
	 //      	alert(error)
	 //      }
	 //    })
    	
  //   }

    render() {
        let barHeight = StatusBar.currentHeight;
        return (
            <View style={{
                backgroundColor: '#fff',
                // paddingTop: barHeight
                paddingBottom: 60
            }}>
                <HomeHeader navigate={this.props.navigate} />
                <FlatList
                    extraData={this.state}
                    initialNumToRender={10}
                    horizontal={false}
                    numColumns={2}
                    columnWrapperStyle={{
                    	paddingLeft: 10,
                    	paddingRight: 10,
						justifyContent: 'space-between',
						alignItems: 'center'
                    }}
                    data={this.state.lists}
                    // 给数组的每一项指定key，避免不必要的render
                    keyExtractor={(item, index) => item.id}
                    // 设置下拉刷新功能的状态
                    refreshing={ this.state.isLoad }
                    // 头部组件
                    ListHeaderComponent={this._headerComponent.bind(this)}
                    // 尾部组件
                    ListFooterComponent={this._bottomComponent.bind(this)}
                    // 给组件设置下拉刷新功能
                    onRefresh={this._onRefresh.bind(this)}
                    // onEndReachedThreshold={0.01}
                    // onEndReached={this._onEndReached.bind(this)}
                    // 渲染数组组件
                    renderItem={({item}) => {
                        return (
                            <TouchableWithoutFeedback onPress={()=>this.props.navigate('NewsDetail')}>
                                <View style={{
					                width: '48.5%',
					                backgroundColor: '#fff'
					            }} key={item.id}>
					                <View style={{paddingBottom: 8}}>
					                    <Image style={{
					                        width: '100%',
					                        height: 125,
					                        borderRadius: 5,
					                        marginBottom: 5
					                    }} source={{uri: item.src}}/>
					                    <Text style={{fontSize: 13, lineHeight: 17, color: '#707070'}} numberOfLines={2}>固特异工艺手工鞋 JACK Adass
					                        PENG 高级定致 制鞋</Text>
					                </View>
					            </View>
                            </TouchableWithoutFeedback>
                        )
                    }}
                />
            </View>
        );
    }

    //当视频开始加载时的回调函数
    loadStart(){
        // alert('开始加载...')
    }

    //当视频加载完毕时的回调函数
    setTime(){
        if(this.state.videoReady){
            // alert('加载完成...');
            this.setState({
                videoReady: false
            })
        }
    }

    //当视频播放完毕时的回调函数
    onEnd(){
        alert('播放完成...')
    }

    //当视频不能加载，或出错后的回调函数
    videoError(){
        alert('视频出错...')
    }

    // 播放视频
    goPlay(){
        // alert(1);
        this.setState({
            isPlay: false
        })
    }
    
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#eeeeee',
    },
    playBtn: {
        position: 'absolute',
        left: '50%',
        top: '50%',
        marginLeft: -26,
        marginTop: -26,
        width: 52,
        height: 52
    }
});